//
//  CateTableViewController.swift
//  MeiTuan
//
//  Created by henaihan on 2017/10/23.
//  Copyright © 2017年 henaihan. All rights reserved.
//

import UIKit

let TAG_TITLE = 1
let TAG_ADDR = 2
let TAG_SALE = 3
let TAG_PIC = 4
let TAG_PRICE = 5

class CateTableViewController: UITableViewController {
    //保存plist所有数据的arrAll数组懒加载
    lazy var allArr:NSMutableArray = { () -> NSMutableArray in
        let tempallArr = NSMutableArray()
        let strPath = Bundle.main.path(forResource: "Cate", ofType: "plist")
        let arr: NSMutableArray = NSMutableArray(contentsOfFile: strPath!)!
        for dict in arr{
            let model: CateModel = CateModel.cateModelWithDict(_dict: dict as! NSDictionary)
            tempallArr.add(model)
        }
        return tempallArr
    }()
    
    var HeaderView = UIView()//标题视图
    var scrollView = UIScrollView()//滚动图片
    var pageControl = UIPageControl()
    
    var images = ["1.jpg","2.jpg","3.jpg"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "美食团购"
        header()
    }
    
    func header(){
        //这是滚动视图作为tableview的headerview
        let w = self.view.frame.size.width
        let h = self.view.frame.size.height
        HeaderView.frame = CGRect(x: 0, y: 0, width: w, height: h*2/6)
        self.tableView.tableHeaderView = HeaderView
        //设置scrollview
        scrollView.frame = CGRect(x: 0, y: 0, width: w, height: h*2/6-20)
        scrollView.contentSize = CGSize(width: w*5, height: scrollView.frame.height)
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        HeaderView.addSubview(scrollView)
        
        pageControl.frame = CGRect(x: w*2/5, y: scrollView.frame.height, width: w*1/5, height: 20)
        pageControl.addTarget(self, action: #selector(pageChanged(_:)), for: UIControlEvents.valueChanged)
        pageControl.numberOfPages = images.count
        pageControl.pageIndicatorTintColor = UIColor.yellow
        pageControl.currentPageIndicatorTintColor = UIColor.red
        pageControl.currentPage = 0
        HeaderView.addSubview(pageControl)
        
        //设置第2-3-4张图片
        for i in 1...self.images.count{
            let imageView = UIImageView(image: UIImage(named: images[i-1]))
            imageView.frame = CGRect(x: w*CGFloat(i), y: 0, width: w, height: scrollView.frame.height)
            scrollView.addSubview(imageView)
            scrollView.delegate = self
        }
        
        //设置第1-5张图片，这之后的图片的顺序是3| 123 |1（图片位置）
        let imageView1 = UIImageView(image: UIImage(named: images.last!))
        imageView1.frame = CGRect(x: 0, y: 0, width: w, height: scrollView.frame.height)
        
        let imageView5 = UIImageView(image: UIImage(named: images.first!))
        imageView5.frame = CGRect(x: w*4, y: 0, width: w, height: scrollView.frame.height)
        
        scrollView.addSubview(imageView1)
        scrollView.addSubview(imageView5)
        
        //设置viewdidload时scrollview的位置
        scrollView.scrollRectToVisible(CGRect(x: w, y:0, width: w, height: h), animated: false)
        //设置定时器
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AutoScroll), userInfo: nil, repeats: true)
    }
    
    @objc func AutoScroll(){
        var page = pageControl.currentPage
        page += 1
        page = page > 2 ? 0 : page //因为总共的索引为0-1-2
        pageControl.currentPage = page
        pageChanged(pageControl)
    }
    
    //点击页控件时事件处理
    @objc func pageChanged(_ sender:UIPageControl) {
        //根据点击的页数，计算scrollView需要显示的偏移量
        var frame = scrollView.frame
        frame.origin.x = frame.size.width * CGFloat(sender.currentPage + 1)
        frame.origin.y = 0
        //展现当前页面内容
        scrollView.scrollRectToVisible(frame, animated:true)
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //计算出是第几页
        let w = self.scrollView.frame.width
        let h = self.scrollView.frame.height
        
        let page = Int(scrollView.contentOffset.x / scrollView.frame.width)
        
        if page == 0{
            self.scrollView.scrollRectToVisible(CGRect(x: CGFloat(images.count)*w, y: 0, width: w, height: h), animated: false)
            pageControl.currentPage = 2
        }else if page == images.count+1{
            self.scrollView.scrollRectToVisible(CGRect(x: w, y: 0, width: w, height: h), animated: false)
            pageControl.currentPage = 0
        }else{
            pageControl.currentPage = page - 1
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    //有几组
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    //每组有几个
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.allArr.count
    }
    
    //每个的内容
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MeiTuanCell.createCell(tableView: tableView)
        let model: CateModel = self.allArr[indexPath.row] as! CateModel
        cell.model = model
        // Configure the cell...
        
        return cell
    }
    
    //每个的高度
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    /*
     //第一种跳转
     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let detail: DetailViewController = storyboard?.instantiateViewController(withIdentifier: "detailView") as! DetailViewController
     let model: CateModel = self.allArr[indexPath.row] as! CateModel
     detail.model = model
     self.navigationController?.pushViewController(detail, animated: true)
     }
     */
    
    //第二种跳转
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model: CateModel = self.allArr[indexPath.row] as! CateModel
        self.performSegue(withIdentifier: "todetail", sender: model)
    }
    
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        let detail: DetailViewController = segue.destination as! DetailViewController
//        detail.model = sender as! CateModel
//    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "欢迎来选购"
    }
    
    override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        return "一共有\(allArr.count)种商品"
    }
}

